﻿/**
 * 定义环形缓冲类
 *
 * @file RingBuffer.h
 * @author Song
 * @date 2011-9-27
 *
 */

#pragma once

namespace helpers {
	
	/// @ingroup helpers
	/// 简单环形内存类
	class SimpleRingBuffer 
	{
	public:
		SimpleRingBuffer(size_t size)
			: _addr(NULL)
			, _size(0)
			, _wpos(0)
		{
			init(size);
		}

		~SimpleRingBuffer()
		{
			cleanup();
		}

		void* alloc(size_t size)
		{
			if (size > _size)
				return NULL;

			if (_wpos + size > _size) {
				_wpos = 0;
			}

			void* buf = (char_t*)_addr + _wpos;
			_wpos += size;
			return buf;
		}

		void free(void* /*memery*/)
		{
			//
		}

	private:
		void init(size_t size)
		{
			_addr = malloc(size);
			_size = size;
			_wpos = 0;
		}

		void cleanup()
		{
			free(_addr);
			_size = 0;
			_wpos = 0;
		}


	private:
		void*			_addr;
		size_t			_size;
		volatile int	_wpos;
	};
}
